package com.android.manghe.detail.activity

import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.base.frame.view.MVPActivity
import com.android.base.view.recycler.RecyclerViewDivider
import com.android.manghe.R
import com.android.manghe.detail.adapter.TrendChartAdapter
import com.android.manghe.detail.model.AuctionHistoryRes
import com.android.manghe.detail.precenter.PTrendChart
import com.android.manghe.view.AutoHeightLayoutManager
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import kotlinx.android.synthetic.main.activity_trend_chart.*
import java.util.*

class TrendChartActivity : MVPActivity<PTrendChart>() {

    private var mAdapter: TrendChartAdapter? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_trend_chart
    }

    override fun initData(savedInstanceState: Bundle?) {
        titleBar.setToolbar("历史成交走势图").setLeftIcon(R.mipmap.icon_back_black).setTitleAndStatusBgColor(R.color.white)
        p.mAuctionId = intent.getStringExtra("auctionId")


        mAdapter = TrendChartAdapter(arrayListOf())
        recyclerView.adapter = mAdapter
        recyclerView.layoutManager = AutoHeightLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        recyclerView.addItemDecoration(RecyclerViewDivider(mContext, LinearLayoutManager.HORIZONTAL))

        p.loadData()
    }

    fun updateView(res: AuctionHistoryRes) {
        lineChart.description.isEnabled = false
        lineChart.setDrawGridBackground(false)
        val xAxis = lineChart.getXAxis()
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.setDrawGridLines(false)
        xAxis.setDrawAxisLine(false)

        val leftAxis = lineChart.axisLeft
        leftAxis.setLabelCount(5, false)
        leftAxis.axisMinimum = 0f // this replaces setStartAtZero(true)

        lineChart.axisRight.isEnabled = false
        if (res.list != null && res.list.size != 0) {
            // 获取的坐标数据集合
            val list = res.list.asReversed()
            val itemList = ArrayList<Entry>()
            for ((i, item) in list.withIndex()) {
                val entry = Entry(item.period, item.price)
                itemList.add(entry)
            }

            val org = ContextCompat.getColor(this, R.color.colorPrimary)
            val d1 = LineDataSet(itemList, "成交记录")
            d1.lineWidth = 1.5f
            d1.color = org
            d1.circleRadius = 2f
            d1.highLightColor = org
            d1.setCircleColor(org)
            d1.setDrawValues(true)

            val lineData = LineData(d1)
            lineChart.data = lineData
            lineChart.animateX(750)

            mAdapter?.setNewData(res.list)
        }
    }
}